const countdownApi = require('../../utils/countdownApi');
const auth = require('../../utils/auth');

Page({
  data: {
    // 列表数据
    countdownList: [],
    loading: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 10,
    
    // 筛选和搜索
    currentTab: 'all',
    searchKeyword: '',
    
    // 统计信息
    statistics: {
      totalEvents: 0,
      upcomingEvents: 0,
      expiredEvents: 0,
      todayEvents: 0
    },
    
    // 弹窗相关
    showModal: false,
    isEdit: false,
    submitting: false,
    formData: {
      id: null,
      eventName: '',
      targetDate: '',
      creator: ''
    },
    
    // 今天日期
    today: ''
  },

  onLoad: function (options) {
    this.initPage();
  },

  onShow: function () {
    this.loadData();
  },

  onPullDownRefresh: function () {
    this.refreshData();
  },

  onReachBottom: function () {
    this.loadMoreData();
  },

  // 初始化页面
  initPage() {
    // 设置今天日期
    const today = new Date();
    const todayStr = today.getFullYear() + '-' + 
                    String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                    String(today.getDate()).padStart(2, '0');
    
    this.setData({
      today: todayStr,
      'formData.creator': auth.getUserInfo()?.nickName || '微信用户'
    });
    
    this.loadData();
  },

  // 加载数据
  async loadData() {
    this.setData({ loading: true });
    
    try {
      // 只加载列表数据
      const listRes = await this.loadCountdownList();
      
      if (listRes.code === 200) {
        this.setData({ 
          countdownList: listRes.data || [],
          hasMore: (listRes.data || []).length >= this.data.pageSize
        });
        console.log('数据加载完成，列表长度:', (listRes.data || []).length);
      } else {
        console.error('数据加载失败:', listRes);
        this.setData({ 
          countdownList: [],
          hasMore: false
        });
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ 
        countdownList: [],
        hasMore: false
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },

  // 加载统计信息
  async loadStatistics() {
    try {
      return await countdownApi.getStatistics();
    } catch (error) {
      console.error('加载统计信息失败:', error);
      return { code: 500, msg: '加载失败' };
    }
  },

  // 加载倒数日列表
  async loadCountdownList() {
    try {
      let response;
      
      console.log('当前标签:', this.data.currentTab);
      console.log('搜索关键词:', this.data.searchKeyword);
      
      switch (this.data.currentTab) {
        case 'upcoming':
          console.log('加载即将到期数据');
          response = await countdownApi.getUpcoming();
          break;
        case 'expired':
          console.log('加载已过期数据');
          response = await countdownApi.getExpired();
          break;
        case 'all':
        default:
          console.log('加载全部数据');
          if (this.data.searchKeyword) {
            console.log('使用搜索API');
            response = await countdownApi.search(this.data.searchKeyword);
          } else {
            console.log('使用列表API');
            response = await countdownApi.getList();
          }
          break;
      }
      
      console.log('API响应:', response);
      
      if (response && response.code === 200) {
        // 处理数据，添加计算字段
        const rawData = response.data || [];
        console.log('原始数据:', rawData);
        
        if (rawData && rawData.length > 0) {
          const processedData = rawData.map(item => {
            const remainingDays = this.calculateRemainingDays(item.targetDate);
            return {
              ...item,
              remainingDays: remainingDays,
              isExpired: remainingDays < 0,
              createTime: this.formatDateTime(item.createTime)
            };
          });
          
          console.log('处理后的数据:', processedData);
          return { ...response, data: processedData };
        } else {
          console.log('没有数据');
          return { code: 200, data: [] };
        }
      } else {
        console.warn('API响应格式不正确:', response);
        return { code: 200, data: [] };
      }
    } catch (error) {
      console.error('加载倒数日列表失败:', error);
      return { code: 500, msg: '加载失败', data: [] };
    }
  },

  // 刷新数据
  async refreshData() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      countdownList: []
    });
    await this.loadData();
  },

  // 加载更多数据
  async loadMoreData() {
    if (!this.data.hasMore || this.data.loading) return;
    
    this.setData({ 
      currentPage: this.data.currentPage + 1,
      loading: true 
    });
    
    try {
      const response = await countdownApi.getPage({
        current: this.data.currentPage,
        size: this.data.pageSize,
        keyword: this.data.searchKeyword,
        creator: this.data.formData.creator
      });
      
      if (response.code === 200) {
        const newData = (response.data.records || []).map(item => {
          const remainingDays = this.calculateRemainingDays(item.targetDate);
          return {
            ...item,
            remainingDays: remainingDays,
            isExpired: remainingDays < 0,
            createTime: this.formatDateTime(item.createTime)
          };
        });
        
        this.setData({
          countdownList: [...this.data.countdownList, ...newData],
          hasMore: newData.length >= this.data.pageSize
        });
      }
    } catch (error) {
      console.error('加载更多失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 计算剩余天数
  calculateRemainingDays(targetDate) {
    if (!targetDate) return 0;
    
    const today = new Date();
    const target = new Date(targetDate);
    const diffTime = target.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    return diffDays;
  },

  // 格式化日期时间
  formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索
  async onSearch() {
    await this.refreshData();
  },

  // 标签切换
  async onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    console.log('切换到标签:', tab);
    
    this.setData({
      currentTab: tab,
      searchKeyword: ''
    });
    
    console.log('当前标签设置为:', this.data.currentTab);
    await this.refreshData();
  },

  // 点击列表项
  onItemTap(e) {
    const item = e.currentTarget.dataset.item;
    wx.showModal({
      title: item.eventName,
      content: `目标日期：${item.targetDate}\n剩余天数：${item.remainingDays}天\n创建人：${item.creator}`,
      showCancel: false
    });
  },

  // 编辑
  onEdit(e) {
    console.log('编辑按钮被点击', e);
    const id = e.currentTarget.dataset.id;
    console.log('编辑ID:', id);
    
    const item = this.data.countdownList.find(item => item.id == id);
    console.log('找到的项目:', item);
    
    if (item) {
      this.setData({
        showModal: true,
        isEdit: true,
        formData: {
          id: item.id,
          eventName: item.eventName,
          targetDate: item.targetDate,
          creator: item.creator
        }
      });
      console.log('编辑弹窗已打开');
    } else {
      wx.showToast({
        title: '未找到该项目',
        icon: 'none'
      });
    }
  },

  // 删除
  onDelete(e) {
    console.log('删除按钮被点击', e);
    const id = e.currentTarget.dataset.id;
    console.log('删除ID:', id);
    
    const item = this.data.countdownList.find(item => item.id == id);
    console.log('找到的项目:', item);
    
    if (item) {
      wx.showModal({
        title: '确认删除',
        content: `确定要删除"${item.eventName}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.deleteCountdown(id);
          }
        }
      });
    } else {
      wx.showToast({
        title: '未找到该项目',
        icon: 'none'
      });
    }
  },

  // 删除倒数日
  async deleteCountdown(id) {
    try {
      wx.showLoading({ title: '删除中...' });
      
      const response = await countdownApi.delete(id);
      
      if (response.code === 200) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 刷新数据
        await this.refreshData();
      } else {
        throw new Error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 添加
  onAdd() {
    this.setData({
      showModal: true,
      isEdit: false,
      formData: {
        id: null,
        eventName: '',
        targetDate: '',
        creator: auth.getUserInfo()?.nickName || '微信用户'
      }
    });
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showModal: false,
      submitting: false
    });
  },

  // 弹窗遮罩点击
  onModalOverlayTap() {
    this.onCloseModal();
  },

  // 弹窗容器点击
  onModalContainerTap() {
    // 阻止事件冒泡
  },

  // 事件名称输入
  onEventNameInput(e) {
    this.setData({
      'formData.eventName': e.detail.value
    });
  },

  // 日期选择
  onDateChange(e) {
    this.setData({
      'formData.targetDate': e.detail.value
    });
  },

  // 创建人输入
  onCreatorInput(e) {
    this.setData({
      'formData.creator': e.detail.value
    });
  },

  // 确认提交
  async onConfirm() {
    const { eventName, targetDate, creator } = this.data.formData;
    
    // 表单验证
    if (!eventName.trim()) {
      wx.showToast({
        title: '请输入事件名称',
        icon: 'none'
      });
      return;
    }
    
    if (!targetDate) {
      wx.showToast({
        title: '请选择目标日期',
        icon: 'none'
      });
      return;
    }
    
    if (!creator.trim()) {
      wx.showToast({
        title: '请输入创建人',
        icon: 'none'
      });
      return;
    }
    
    // 检查日期是否为未来日期
    const today = new Date();
    const target = new Date(targetDate);
    if (target <= today) {
      wx.showToast({
        title: '目标日期必须是未来日期',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ submitting: true });
    
    try {
      wx.showLoading({ 
        title: this.data.isEdit ? '更新中...' : '添加中...' 
      });
      
      let response;
      if (this.data.isEdit) {
        response = await countdownApi.update(this.data.formData);
      } else {
        response = await countdownApi.add(this.data.formData);
      }
      
      if (response.code === 200) {
        wx.showToast({
          title: this.data.isEdit ? '更新成功' : '添加成功',
          icon: 'success'
        });
        
        this.onCloseModal();
        await this.refreshData();
      } else {
        throw new Error(response.msg || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
      wx.hideLoading();
    }
  },

  // 添加测试数据
  async addTestData() {
    try {
      wx.showLoading({ title: '添加测试数据...' });
      
      const testEvents = [
        {
          eventName: '期末考试',
          targetDate: '2024-12-25',
          creator: '张老师'
        },
        {
          eventName: '家长会',
          targetDate: '2024-12-20',
          creator: '李老师'
        },
        {
          eventName: '运动会',
          targetDate: '2024-12-15',
          creator: '王老师'
        }
      ];
      
      for (const event of testEvents) {
        try {
          await countdownApi.add(event);
        } catch (error) {
          console.error('添加测试事件失败:', error);
        }
      }
      
      wx.showToast({
        title: '测试数据添加完成',
        icon: 'success'
      });
      
      // 刷新数据
      await this.refreshData();
    } catch (error) {
      console.error('添加测试数据失败:', error);
      wx.showToast({
        title: '添加测试数据失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  }
});